package com.ericsson.common.util;

import java.util.Map;
import java.util.Set;

/**
 * 集合处理工具类
 *
 * @author zhuguangrui
 */
public class CollectionUtils {

    /**
     * map合并，相同的key将value合并
     * @param map1
     * @param map2
     * @return
     */
    public static Map<String, Set<String>> mergeMap(Map<String, Set<String>> map1, Map<String, Set<String>> map2) {
        if (map1 == null || map1.isEmpty()) {
            return map2;
        }
        if (map2 == null || map2.isEmpty()) {
            return map1;
        }
        if (map1.size() < map2.size()) {
            return getMap(map1, map2);
        } else {
            return getMap(map2, map1);
        }
    }

    /**
     * 遍历size小的集合将重复的合并，然后追加上key不重复的
     * @param small
     * @param big
     * @return
     */
    private static Map<String, Set<String>> getMap(Map<String, Set<String>> small, Map<String, Set<String>> big) {
        for (Map.Entry<String, Set<String>> entry : small.entrySet()) {
            if (big.containsKey(entry.getKey())) {
                entry.getValue().addAll(big.get(entry.getKey()));
                big.remove(entry.getKey());
            }
        }
        if(!big.isEmpty()) {
            small.putAll(big);
        }
        return small;
    }


}
